# -*- coding: utf-8 -*-
# @File: backend => test.py
# @CreateTime: 2025/8/25 11:07
# @Author: EvanZhang
# @Info:
import redis.asyncio as pyredis
from fastapi import APIRouter, HTTPException, Depends
from fastapi.responses import JSONResponse

from apps.models import User
from apps.schemas.test import UserTestRequest, UserTestResponse, UserListTestResponse
from apps.schemas.user_schema import UserLoginResponse, UserBase
from apps.settings.redis import init_redis_pool
from tortoise.queryset import QuerySet

from apps.utils.jwt import verify_jwt_token

myTest = APIRouter()

@myTest.get("/testjsonresponse",summary="测试连通性")
async def test_endpoint():
    return JSONResponse(content={"message": "这是一个测试接口"})

@myTest.get("/testerror",summary="测试错误处理")
async def test_error():
    try:
        raise HTTPException(status_code=400, detail="这是一个错误测试")
    except Exception as e:
        raise HTTPException(status_code=500, detail="测试错误,返回信息") from e

@myTest.post('/redis',summary="测试Redis缓存是否可用")
async def test_redis(key: str, value: str, redis: pyredis.Redis = Depends(init_redis_pool)):
    # 测试 Redis 连接和基本操作
    try:
        result = await redis.set(key, value)
        return JSONResponse(content={"message": "Data cached successfully", "result": result})
    except Exception as e:
        raise HTTPException(status_code=400,detail=str(e))

@myTest.post('/add2mysql',response_model=UserTestResponse,summary="测试添加用户接口")
async def add_data_to_sql(user:UserTestRequest):
    try:
        result = await User.create(**user.model_dump())
        return result
    except Exception as e:
        print(e)
        raise HTTPException(status_code=403,detail='出现异常，请重试')

@myTest.get('/get5mysql',response_model=UserListTestResponse,summary='测试查询用户信息')
async def get_data_from_mysql():
    try:
        res = await User.filter()
        # total = len(res)
        total = 1
        print(res[0])
        if res:
            return {'total':total,'users':res}
        else:
            raise HTTPException(status_code=404, detail="数据库中暂无数据，请添加")
    except HTTPException:
        raise
    except Exception as e:
        print(e)
        raise HTTPException(status_code=403, detail="发生异常")

@myTest.get('/testJWT',summary='测试JWT鉴权是否可用')
async def test_jwt(user: UserBase = Depends(verify_jwt_token)):
    return JSONResponse(content={"message": f"Hello, {user.username}. JWT鉴权成功!"})


